package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class StatementServiceImpl implements IStatementService {

    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private StatementItemMapper statementItemMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<Statement>(statementMapper.selectForList(qo));
    }


    @Override
    public void save(Statement statement) {
        // 状态设置为消费，因为状态是消费中，所以不管你怎么绕过后台，最后还是要进行结算支付的
        statement.setStatus(Statement.STATUS_CONSUME);
        statementMapper.insert(statement);
    }

    @Override
    public Statement get(Long id) {
        return statementMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(Statement statement) {
        // 只有在消费中的状态才能进行编辑
        Statement oldObj = this.get(statement.getId());
        if (Statement.STATUS_PAID.equals(oldObj.getStatus())){
            throw new BusinessException("只有在消费状态中的结算单才可以进行编辑");
        }
        statementMapper.updateByPrimaryKey(statement);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            statementMapper.deleteByPrimaryKey(dictId);
            // 删除掉结算表中的数据外，还要删除明细表中的数据
            statementItemMapper.deleteByStatementId(dictId);
        }
    }

    @Override
    public List<Statement> list() {
        return statementMapper.selectAll();
    }

    @Override
    public void updateAmount(Long statementId, BigDecimal totalAmount, BigDecimal totalQuantity, BigDecimal disCountPrice) {
        statementMapper.updateAmount(statementId,totalAmount,totalQuantity,disCountPrice);
    }

    @Override
    public void updatePayStatus(Long statementId, Integer status, Long userId) {
        statementMapper.updatePayStatus(statementId,status,userId);
    }

    @Override
    public Statement getByAppointmentId(Long appointmentId) {
        return statementMapper.getByAppointmentId(appointmentId);
    }

}
